package com.daxue.eurekaclientuserservice.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import static com.daxue.eurekaclientuserservice.config.ClientConfig.ORM_PROVIDE_SERVICE;

/**
 * @author daxue0929
 * @date 2021/03/25
 **/
@RestController
public class UserController {

    final RestTemplate restTemplate;

    public UserController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping(value = "/user/hello")
    public String hello(@RequestBody Map map) {
        System.out.println(map.toString());
        return "hello";
    }

    @GetMapping("/fromOrGetUser")
    @HystrixCommand(fallbackMethod = "fromOrmGetUserFallBack") // 服务调用失败，的降级处理走fromOrmGetUserFallBack()逻辑
    public Map fromOrmGetUser() {
        Map forObject = restTemplate.getForObject(ORM_PROVIDE_SERVICE + "/getUser", Map.class);
        return forObject;
    }


    public Map fromOrmGetUserFallBack() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "服务调用失败");
        return map;
    }

    @GetMapping("/user/test")
    public void test(HttpServletRequest httpServletRequest) {
        String remoteAddr = getRemoteAddr(httpServletRequest);
    }

    public String getBodyString(HttpServletRequest request) {

        StringWriter stringWriter = new StringWriter();
        try {
            IOUtils.copy(request.getInputStream(), stringWriter);
            String body = stringWriter.toString();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}
